package com.alifi.crm.web.home.screen;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alibaba.platform.buc.sso.common.dto.SimpleSSOUser;
import com.alifi.crm.biz.lotteryzf.LotteryzfManager;
import com.alifi.crm.dal.object.WinRecordDO;

/**
 * 
 * 
 * @author wb_liangzhou.yan
 * @version $Id: Lottery.java, v 0.1 2013-4-24 下午04:43:42 wb_liangzhou.yan Exp $
 */
public class Payluck {
    
    private static final Logger      logger = LoggerFactory.getLogger(Payluck.class);   
    
    @Resource(name = "lotteryzfManager")
    private LotteryzfManager lotteryzfManager;
    
    public void execute(HttpServletRequest request, HttpServletResponse response,final Context ctx){
        try{
            if(StringUtil.equalsIgnoreCase((String)ctx.get("action"), "true")){   //如果经过action，直接返回
                return;
            }
            
            SimpleSSOUser user = SimpleUserUtil.findUser(request);   // 姓名: lastName   花名: nickNameCn 
            
            if((user==null)||StringUtil.isBlank(user.getEmpId())){   //检查
                logger.error("没有获得您的登录信息，请与管理员联系.电话: 13805730726");
                ctx.put("error","没有获得您的登录信息，请与管理员联系.电话: 13805730726");
                return;
            }
            
            //加上访问日志
            lotteryzfManager.insertLog(user.getEmpId(), user.getLastName(), user.getNickNameCn());
            
            ctx.put("user", user);
            ctx.put("employeeNum", user.getEmpId());
            
            //获取中奖信息
            ctx.put("lotteryInfos", convertToListString(lotteryzfManager.getWinRecords()));
            
            //增加转发次数
            lotteryzfManager.addTransmitLog(request.getParameter("employee_num"),user.getEmpId());
        }catch (Exception e){
            ctx.put("error", e.getMessage());
            logger.error(e);  
        }
        
    }
    
    private List<WinRecordDO> convertToListString(List<WinRecordDO> winRecords){
    	 Date   curDate   =   new   Date(System.currentTimeMillis());//获取当前时间     
    	  SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd"); 
        List<WinRecordDO> lotteryInfos = new ArrayList<WinRecordDO>();
        if(CollectionUtils.isEmpty(winRecords)){
            return null;
        }
        for(WinRecordDO winRecord : winRecords){
            WinRecordDO winRecordDO = new WinRecordDO();
            String name = "";
            if(StringUtils.isNotBlank(winRecord.getNickName())){
                name = winRecord.getNickName();
            }else{
                name = winRecord.getRealName();
            }
            String jiangpinName = "";
            if(winRecord.getPrizeType().equals("2")){
            	jiangpinName = "1元集分宝";
            } 
            if(winRecord.getPrizeType().equals("3")){
            	jiangpinName = "5元集分宝";
            } 
            if(winRecord.getPrizeType().equals("4")){
            	jiangpinName = "10元集分宝";
            } 
            if(winRecord.getPrizeType().equals("6")){
            	jiangpinName = "阿里巴巴LOGO雨伞";
            } 
            if(winRecord.getPrizeType().equals("5")){
            	jiangpinName = "阿里金仔";
            } 
            //sb.append("<li class=\"\">");
            String serSignName = name;
            winRecordDO.setNickName(serSignName);
            //sb.append("<span class=\"u-nick\">"+serSignName+"</span>");
            //sb.append("<span class=\"u-time\">于"+ formatter.format(winRecord.getGmtCreated()) +"抽奖成功</span>");
            winRecordDO.setPrizeType("于"+ formatter.format(winRecord.getGmtCreated()) +"抽奖并转发成功");
            //sb.append("<span class=\"u-getnum\">获得" + jiangpinName +"</span>");
            winRecordDO.setRealName("获得" + jiangpinName);
            lotteryInfos.add(winRecordDO);
        }
        
        return lotteryInfos;
    }
    
    /**
     * 字符串转化显示
     * <pre>
     * convertString(null)      = null
     * convertString("fffff")        = *fff
     * convertString("fff")       = fff
     * convertString("你好啊")     = *好啊
     * convertString("好啊")     = *啊
     * convertString("啊")     = 啊
     * </pre>
     * 
     * @param str
     * @return 转化后的字符串
     */
    public static String convertString(String str){
        StringBuffer sb = new StringBuffer();
        if(StringUtil.isBlank(str)){
            return null;
        }
        boolean isGB2312 = isGB2312(str);
        if (isGB2312) {
            if(str.length() > 1){
                for (int i = 0; i < str.length() -2; i++) {
                    sb.append("*");
                }
                sb.append(str.substring(str.length() -1));
            } else{
                sb.append(str);
            }
        }else{
            if(str.length() > 2){
                sb.append("*").append(str.substring(str.length() -2));
            }else if(str.length() == 2){
                sb.append(str);
            }
        }
        return sb.toString();
    }

    /**
     * 判断是不是中文
     * 
     * @param str 
     * @return
     */
    public static boolean isGB2312(String str) {
        if(StringUtil.isBlank(str)){
            return false;
        }
        char[] chars = str.toCharArray();
        boolean isGB2312 = false;
        for (int i = 0; i < chars.length; i++) {
            byte[] bytes = ("" + chars[i]).getBytes();
            if (bytes.length == 2) {
                int[] ints = new int[2];
                ints[0] = bytes[0] & 0xff;
                ints[1] = bytes[1] & 0xff;
                if (ints[0] >= 0x81 && ints[0] <= 0xFE && ints[1] >= 0x40 && ints[1] <= 0xFE) {
                    isGB2312 = true;
                    break;
                }
            }
        }
        return isGB2312;
    }
    
}
